import 'dart:math';
import 'package:flutter/material.dart';

class LetterPainter extends CustomPainter {
  final String letter;
  final Color? lineColor;
  final Color? color;

  const LetterPainter(
      {required this.letter,
      this.lineColor,
      this.color});

  @override
  void paint(Canvas canvas, Size size) {
    Color finalLineColor = lineColor ?? Color(0xFF41605F);
    double lineHeight = min(size.width / letter.length, size.height / 3 * 2);
    double singleStrokeWidth = lineHeight / 60;
    Paint normalPaint = Paint()
      ..color = finalLineColor
      ..strokeWidth = singleStrokeWidth
      ..style = PaintingStyle.stroke;
    Paint boldPaint = Paint()
      ..color = finalLineColor
      ..strokeWidth = singleStrokeWidth * 1.5
      ..style = PaintingStyle.stroke;

    double centerY = size.height / 2;
    double c = lineHeight / 4.3;

    double firstLineY = centerY - c * 3;
    canvas.drawLine(
        Offset(0, firstLineY), Offset(size.width, firstLineY), boldPaint);
    double secondLineY = centerY - c;
    canvas.drawLine(
        Offset(0, secondLineY), Offset(size.width, secondLineY), normalPaint);
    double thirdLineY = centerY + c;
    canvas.drawLine(
        Offset(0, thirdLineY), Offset(size.width, thirdLineY), normalPaint);
    double fourthLineY = centerY + c * 3;
    canvas.drawLine(
        Offset(0, fourthLineY), Offset(size.width, fourthLineY), boldPaint);

    // 绘制一个拼音
    TextPainter textPainter = TextPainter(
      text: TextSpan(
        text: letter,
        style: TextStyle(
            height: 1,
            color: color,
            fontSize: lineHeight,
            fontFamily: 'PinYin'),
      ),
      textDirection: TextDirection.ltr,
    );

    textPainter.layout(maxWidth: size.width);
    textPainter.paint(
      canvas,
      Offset(
        (size.width - textPainter.width) / 2,
        (size.height - textPainter.height) / 2 - textPainter.height / 14,
      ),
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

class LetterLineBox extends StatefulWidget {
  final String letter;
  final Color? lineColor;
  final Color? color;

  const LetterLineBox({
    super.key,
    required this.letter,
    this.lineColor,
    this.color,
  });

  @override
  State<LetterLineBox> createState() => _LetterLineBoxState();
}

class _LetterLineBoxState extends State<LetterLineBox> {
  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: 3 / 1,
      child: CustomPaint(
          painter: LetterPainter(
        letter: widget.letter,
        lineColor: widget.lineColor,
        color: widget.color,
      )),
    );
  }
}
